package com.yanghs.common.controller;

import com.yanghs.common.service.IUserService;
import com.yanghs.shiro.exception.CustomAuthenticationException;
import com.yanghs.shiro.realm.UserRealm;
import com.yanghs.shiro.token.UserToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author yanghs
 * @Description:
 * @date 2018/3/5 10:17
 */
@Controller
public class UserController {
    //注入userservice
    @Resource(name = "userService")
    IUserService userService;
    @RequestMapping(value = "/dologin.do",method = RequestMethod.POST)
    public @ResponseBody String dologin(@RequestParam Map map) {
        String message = "success";
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        UserToken token = new UserToken(username,password);
        Subject currentUser =  SecurityUtils.getSubject();
        try {
            currentUser.login(token);
            currentUser.getSession().setAttribute("account",username);
        }catch (CustomAuthenticationException e){
            return e.getMessage();
        }catch (UnknownAccountException e){
            message = "账户不存在";
        }catch (IncorrectCredentialsException e){
            message = "账户/用户名错误";
        }
        return  message;
    }

    @RequestMapping(value = "/login.do",method = RequestMethod.GET)
    public String login(){
        return "login";
    }


    /**
     * 手动清楚权限信息
     * @return
     */
    @RequestMapping(value = "/clearCache.do",method = RequestMethod.GET)
    @ResponseBody
    public String clearCache(){
        //清除缓存方法
        RealmSecurityManager realmSecurityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        UserRealm userRealm = (UserRealm) realmSecurityManager.getRealms().iterator().next();
        userRealm.clearCachedAuthorizationInfo();

        return "清除权限缓存成功";
    }
}
